//
//  SpiteView.m
//  制作图标
//
//  Created by mac on 2017/8/28.
//  Copyright © 2017年 yangweiwei. All rights reserved.
//

#import "SpiteView.h"
#import "CImageUtil.h"
#import "ComputingAngleModel.h"
#import "UIView+CustomeLine.h"
@implementation SpiteView

//CGRect rectScale(CGRect rc, float xs, float ys)
//{
//    rc.size = CGSizeMake(rc.size.width*xs, rc.size.height*ys);
//    
//    return rc;
//}
- (void)setLineViews{
    [self rightLine:[UIColor blueColor] andLineWide:2];
    [self leftLine:[UIColor blueColor] andLineWide:2];
    [self toupLine:[UIColor blueColor] andLineHigh:2];
    [self downLine:[UIColor blueColor] andLineHigh:2];
    self.imageView.sd_layout.centerXEqualToView(self).centerYEqualToView(self); 
    
    self.rotateImageView.sd_layout.rightSpaceToView(self, -self.rotateImageView.width/4).bottomSpaceToView(self, -self.rotateImageView.height/4).self.widthIs(self.cancelImageView.frame.size.width).heightIs(self.cancelImageView.frame.size.height);

}
- (instancetype)initWithFrame:(CGRect)frame withImage:(UIImage *)image;{

    self = [super initWithFrame:frame];
    if (self != nil) {
        self.isEditting = YES;
//        self.layer.cornerRadius = 8.0;
//        self.layer.masksToBounds = YES;
//        self.layer.borderWidth = 1.0;
//        self.layer.borderColor = [UIColor blueColor].CGColor;
       
               oldFrame = frame;
        oldPoint = self.center;
        
        
        _imageView = [[UIImageView alloc] initWithImage:image];
//        self.imageView.image = [UIImage imageNamed:@"deco_1"];
        self.imageView.frame = [self rectScaleCgrect:self.frame andFloatXS:0.6 andFloatYS:0.6];
        self.imageView.center = self.center;
        [self addSubview:_imageView];
        self.imageView.sd_layout.centerXEqualToView(self).centerYEqualToView(self); 
        
        
         
        
        _cancelImageView = [[UIImageView alloc] initWithImage:[CImageUtil imageFromFile:@"cancelImg.png"]];
        self.cancelImageView.userInteractionEnabled = YES;
         [self addSubview:_cancelImageView];
        _cancelImageView.frame = [self rectScaleCgrect:_cancelImageView.frame andFloatXS:0.6 andFloatYS:0.6];
        _cancelImageView.contentMode = UIViewContentModeScaleAspectFill;
        _cancelImageView.center = self.bounds.origin;
        [self bringSubviewToFront:_cancelImageView];
        UITapGestureRecognizer *tapCancelImg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancle)];
        [self.cancelImageView addGestureRecognizer:tapCancelImg];
        
        
        _rotateImageView = [[UIImageView alloc] initWithImage:[CImageUtil  imageFromFile:@"roatImg.png"]];
        self.rotateImageView.userInteractionEnabled = YES;
        [self addSubview:_rotateImageView];
        self.rotateImageView.alpha = 1.0;
         [self bringSubviewToFront:_rotateImageView];
        self.rotateImageView.sd_layout.rightSpaceToView(self, -self.rotateImageView.width/4).bottomSpaceToView(self, -self.rotateImageView.height/4).self.widthIs(self.cancelImageView.frame.size.width).heightIs(self.cancelImageView.frame.size.height);
         
         self.userInteractionEnabled = TRUE;
        self.backgroundColor = [UIColor clearColor];
        
        [self setLineViews];
        _isEditting = FALSE;
    }
    return self;

}
//- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.superview];
     
    if (_isEditting) {
        if (!isTransforming) {
            self.center = CGPointMake(point.x+touchOffset.x, point.y+touchOffset.y);		
        } else {
//            CGPoint curOffset;
//            curOffset = CGPointMake(self.center.x-point.x, self.center.y-point.y);
//            
//            float preLen = sqrtf(touchOffset.x*touchOffset.x + touchOffset.y*touchOffset.y);
//            float curLen = sqrtf(curOffset.x*curOffset.x + curOffset.y*curOffset.y);
//            float ratioLen = curLen/preLen;
//            
//            float preAngle = atan2f(touchOffset.y, touchOffset.x);
//            float curAngle = atan2f(curOffset.y, curOffset.x);
//            float deltaAngle = curAngle-preAngle;
//            
//            CGAffineTransform at;
//            at = CGAffineTransformRotate(startTransform, deltaAngle);
//            at = CGAffineTransformScale(at, ratioLen, ratioLen);
//            
//            self.transform = at;
//            
//            CGAffineTransform it;
//            it = CGAffineTransformInvert(self.transform);
//            _rotateImageView.transform = it;
//            _cancelImageView.transform = it;
//            
        }		
    } else {
        
        [self begainAndEndMoves:touches];
    }
}
- (void)begainAndEndMoves:(NSSet *)touches{

    UITouch* touch = [touches anyObject];
    CGPoint translation = [touch locationInView:self.superview.superview];
    
//            NSLog(@"oooooooooooooooo %f--%f", translation.x, translation.y);
    //        NSLog(@"方向==%ld", (long)[ComputingAngleModel accordingToTheThreePointsWhetherClockwiseOrCounterclockwise_OnePoint:self.center andTwopoint:[self viewCenter:self.rotateImageView] andThreePoint:translation]);
    CGAffineTransform   at;
    at =  CGAffineTransformRotate(self.transform, [ComputingAngleModel angleForOriginPoint:[self viewCenter:self] StartPoint:[self viewCenter:self.rotateImageView] EndPoint:translation]);
    float sx = [ComputingAngleModel distanceFromPointX:[self viewCenter:self.rotateImageView] distanceToPointY:translation andOriginPoint:[self viewCenter:self]];
    at = CGAffineTransformScale(at, sx, sx);
    
    
    self.transform = at;

}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    
    CGPoint point = [touch locationInView:self.superview.superview];
    
    isTransforming = FALSE;
    
    if (_isEditting) {
        
    } else {
         [self begainAndEndMoves:touches];
        if (CGRectContainsPoint(self.frame, point)) {
//            if ([self.superview isKindOfClass:[SpriteContainerView class]]) {
//                [(SpriteContainerView*)self.superview unselectAllSprite];
//            }
        
            self.isEditting = TRUE;
            [self.superview bringSubviewToFront:self];
        }
    }
//    [self begainAndEndMoves:touches];
//    [self setNeedsDisplay];
    
    

}


- (CGRect)rectScaleCgrect:(CGRect)rc andFloatXS:(float)xs andFloatYS:(float)ys{
    rc.size = CGSizeMake(rc.size.width*xs, rc.size.height*ys);
    return rc;
}

- (void)cancle{
    [self removeFromSuperview];
}
 
 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

//    for (UIView *view in self.subviews) {
//        if (view.width == 2 || view.height == 2) {
//            [view removeFromSuperview];
//        }
//    }
[self setLineViews];
    UITouch* touch = [touches anyObject];
    begainPoint = [touch locationInView:self.superview.superview];
    startTransform = self.transform;
    if ([touches anyObject].view == self.rotateImageView) {
        _isEditting = NO;
        NSLog(@"yes");
    }else{
        _isEditting = YES;
        
        self.cancelImageView.hidden = NO;
        self.rotateImageView.hidden = NO;
        NSLog(@"no");
    }
    
    
    CGPoint pointInSelf = [touch locationInView:self];
    if (CircleContainsPoint1(self.cancelImageView.frame, pointInSelf)) {
        [self removeFromSuperview];
    }  
//    if (CGRectContainsPoint(self.frame, pointInSelf) && CGRectContainsPoint(self.cancelImageView.frame, pointInSelf)) {
//        [self removeFromSuperview];
//    }
    
//    [self hitTest:begainPoint withEvent:event];
}

//- (void)setIsEditting:(bool)isEditting{
//
//    if (_isEditting == isEditting) {
//        return;
//    }
//    _isEditting = isEditting;
//    [self setNeedsDisplay];
//}

- (CGPoint)viewCenter:(UIView *)view{

    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    CGRect rect=[view convertRect: view.bounds toView:window];
    UIView *view1 =[[UIView alloc] init];
    view1.frame = rect;
    return view1.center;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{

    if (!self.clipsToBounds && !self.hidden && self.alpha > 0) {
        UIView *result = [super hitTest:point withEvent:event];
        if (result) {
            return result;
        } else {
            for (UIView *subview in self.subviews.reverseObjectEnumerator) {
                CGPoint subPoint = [subview convertPoint:point fromView:self];
                result = [subview hitTest:subPoint withEvent:event];
                if (result) {
                    return  result;
                }  
            }
        }
    }
    return nil;
}


@end
